//
//  HJVisitFriendInfoController.m
//  Keping
//
//  Created by a on 2017/8/29.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "HJVisitFriendInfoController.h"
#import "HJVisitFriendRequest.h"
#import "HJVisitFriendMessageCell.h"
#import "HJVisitFriendModel.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetItem.h>
#import "KUserData.h"
#import "GPIMController.h"

@interface HJVisitFriendInfoController ()<UITableViewDelegate,UITableViewDataSource>
/**
 tableView
 */
@property(nonatomic,weak)UITableView *tableView;
/**
 数据源
 */
@property (nonatomic, strong)NSMutableArray *dataAry;
/**PreAppointmentTypeForVisit 使用的数据源*/
@property (nonatomic, strong) HJVisitFriendInfoModel *visitFriendInfoModel;
/**PreAppointmentTypeForInvte 存储的数据*/
@property (nonatomic, strong) NSMutableDictionary *invteDict;
@end

@implementation HJVisitFriendInfoController
-(NSMutableArray *)dataAry
{
    if (!_dataAry) {
        _dataAry=[NSMutableArray arrayWithObjects:@[@"* Full Name"],@[@"* Mobile Phone Number"],@[@"Email Address"],@[@"Vehicle Plate Number"],@[@"Message"], nil];
    }
    return _dataAry;
}

- (NSMutableDictionary *)invteDict {
    if (!_invteDict) {
        _invteDict = [[NSMutableDictionary alloc] init];
    }
    return _invteDict;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self getData];
}

- (void)getData {
    if (self.preType == PreAppointmentTypeForVisit) {
        [super getData];
        [self showLoading];
        WEAKSELF
        HJVisitFriendInfoRequest *info = [[HJVisitFriendInfoRequest alloc] initWithKey:[KPartyView unarchive].uid];
        [info startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            HJVisitFriendInfoModel *model  = [HJVisitFriendInfoModel modelWithJSON:request.responseData];
            weakSelf.visitFriendInfoModel = model;
            if (model.statusCode == 200) {
                [weakSelf.tableView reloadData];
            } else {
                [weakSelf showErrorText:model.msg errCode:model.statusCode];
            };
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf showErrorText:request.responseString];
        }];
    }
}

-(void)setUI
{
    if (self.preType == PreAppointmentTypeForVisit) {
        self.navigationItem.title=@"Visit a Friend";
    } else {
        self.navigationItem.title=@"Detail";
    }
    UITableView*tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.backgroundColor=[UIColor colorWithHexString:@"#f2f1f6"];
    [self.view addSubview:tableView];
    self.tableView=tableView;
    
    
    //添加table尾部
    UIView*footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, K_FactorH(100))];
    tableView.tableFooterView=footerView;
    footerView.backgroundColor=[UIColor clearColor];
    CGFloat margin =K_FactorW(20);
    UIButton*addBtn=[[UIButton alloc]initWithFrame:CGRectMake(margin, K_FactorH(30), footerView.width-2*margin, footerView.height-K_FactorH(30)-margin)];
    [footerView addSubview:addBtn];
    addBtn.layer.cornerRadius=addBtn.height/2;
    addBtn.layer.masksToBounds=YES;
    [addBtn setBackgroundColor:[UIColor colorWithHexString:@"#6853fa"] forState:UIControlStateNormal];
    [addBtn setTitle:@"Send Request" forState:UIControlStateNormal];
    addBtn.titleLabel.font=[UIFont boldSystemFontOfSize:20];
    [addBtn addTarget:self action:@selector(clickSendRequest) forControlEvents:UIControlEventTouchUpInside];

}
-(void)clickSendRequest
{
    HJVisitFriendInfoSendRequest *request = [[HJVisitFriendInfoSendRequest alloc] init];
    if (self.preType == PreAppointmentTypeForVisit) {
        NSString *vehicleNumber = [self.invteDict objectForKey:@"vehicleNumber"];
        if (StringNotEmpty(vehicleNumber)) {
            vehicleNumber = [self.invteDict objectForKey:@"vehicleNumber"];
        } else {
            vehicleNumber = self.visitFriendInfoModel.partyView.verificationCode ? self.visitFriendInfoModel.partyView.verificationCode : @"";
        }
    
        request.params = @{
                           @"date":self.date,
                           @"email":self.visitFriendInfoModel.partyView.email,
                           @"friendId":self.relationFriendID,
                           @"fullName":self.visitFriendInfoModel.partyView.nickName,
                           @"message":StringNotNull([self.invteDict objectForKey:@"message"]) ? [self.invteDict objectForKey:@"message"] : @"",
                           @"phone":self.visitFriendInfoModel.partyView.phone,
                           @"time":[self.time stringByAppendingString:@":00"],
                           @"vehicleNumber":vehicleNumber
                           };
        WEAKSELF
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            NSInteger code = [[dict objectForKey:@"statusCode"] integerValue];
            if (code == 200) {
                [weakSelf showSuccess:@"Visitation request sent"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"KPushAppOintmentsForVisit" object:nil];
                [weakSelf.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            } else {
                [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:code];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf showError:request.error];
        }];
    } else {
        HJVisitFriendAddRequest *request = [[HJVisitFriendAddRequest alloc] init];
        request.params = @{
                           @"inviteId":self.relationFriendID,
                           @"email":[self.invteDict objectForKey:@"email"] ? [self.invteDict objectForKey:@"email"] : @"",
                           @"fullName":[self.invteDict objectForKey:@"fullName"] ? [self.invteDict objectForKey:@"fullName"] : @"",
                           @"message":[self.invteDict objectForKey:@"message"] ? [self.invteDict objectForKey:@"message"] : @"",
                           @"phone":[self.invteDict objectForKey:@"phone"] ? [self.invteDict objectForKey:@"phone"] : @"",
                           @"vehicleNumber":[self.invteDict objectForKey:@"vehicleNumber"] ? [self.invteDict objectForKey:@"vehicleNumber"] : @""
                           };
        WEAKSELF
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            NSInteger code = [[dict objectForKey:@"statusCode"] integerValue];
            if (code == 200) {
                [weakSelf showSuccess:@"Invitation Sent"];
//                [weakSelf actionForShare];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:code];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf showError:request.error];
        }];
    }
}

- (void)actionForShare {

    NSString *shareText = [NSString stringWithFormat:@"Invite Guests:\nFull Name: %@ \nPhone: %@ \nEmail: %@ \nVehicle Plate Number: %@ \nMessage: %@",[self.invteDict objectForKey:@"nickName"] ? [self.invteDict objectForKey:@"nickName"] : @"",[self.invteDict objectForKey:@"phone"] ? [self.invteDict objectForKey:@"phone"] : @"",[self.invteDict objectForKey:@"email"] ? [self.invteDict objectForKey:@"email"] : @"", [self.invteDict objectForKey:@"vehicleNumber"] ? [self.invteDict objectForKey:@"vehicleNumber"] : @"", [self.invteDict objectForKey:@"message"] ? [self.invteDict objectForKey:@"message"] : @""];
    WEAKSELF
    SSUIShareActionSheetItem *item = [SSUIShareActionSheetItem itemWithIcon:[UIImage imageNamed:@"ic_friend"] label:@"Friends" onClick:^{
        GPIMController *vc = [[GPIMController alloc] initWithIndex:1 isShare:YES shareText:shareText];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSArray *array = @[@(SSDKPlatformTypeSMS),item,@(SSDKPlatformTypeWhatsApp)];
    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:shareText
                                     images:nil
                                        url:[NSURL URLWithString:@"https://www.linktime.com.my/"]
                                      title:@"Invite Guests"
                                       type:SSDKContentTypeText];
    //有的平台要客户端分享需要加此方法，例如微博
    [shareParams SSDKEnableUseClientShare];
    //2、分享（可以弹出我们的分享菜单和编辑界面）
    [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                             items:array
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                       case SSDKResponseStateBegin:
                       {
                           UIBarButtonItem* item = [UIBarButtonItem appearance];
                           [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kBlueColor} forState:UIControlStateNormal];
                           [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kBlueColor}];
                           //设置UI等操作
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
                           UIBarButtonItem* item = [UIBarButtonItem appearance];
                           [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kWhiteColor} forState:UIControlStateNormal];
                           [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kWhiteColor}];
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Share Success!"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           [self.navigationController popViewControllerAnimated:YES];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIBarButtonItem* item = [UIBarButtonItem appearance];
                           [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:kWhiteColor} forState:UIControlStateNormal];
                           [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:kBoldFont(20),NSForegroundColorAttributeName:kWhiteColor}];
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Share Fail!"
                                                                           message:[NSString stringWithFormat:@"%@",error]
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           [alert show];
                           break;
                       }
                        case SSDKResponseStateCancel:
                           [self.navigationController popViewControllerAnimated:YES];
                           break;
                       default:
                           break;
                   }
               }
     ];
}

#pragma mark --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataAry.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataAry[section] count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row     = indexPath.row;
    WEAKSELF
    if (section == self.dataAry.count - 1) {
        HJVisitFriendMessageCell*cell=[HJVisitFriendMessageCell cellWithTableView:tableView];
        cell.title = self.dataAry[section][row];
        cell.visitFriend = ^(id cell, NSString *contet) {
            [weakSelf.invteDict setObject:contet forKey:@"message"];
        };
        return cell;
    } else {
        HJVisitFriendViewCell*cell = [HJVisitFriendViewCell cellWithTableView:tableView];
        cell.title = self.dataAry[section][row];
        cell.visitFriend = ^(id cell, NSString *contet) {
            NSIndexPath *indexPath = [weakSelf.tableView indexPathForCell:cell];
            NSInteger sectionTmp = indexPath.section;
            switch (sectionTmp) {
                case 0:
                    [weakSelf.invteDict setObject:contet forKey:@"fullName"];
                    break;
                case 1:
                    [weakSelf.invteDict setObject:contet forKey:@"phone"];
                    break;
                case 2:
                    [weakSelf.invteDict setObject:contet forKey:@"email"];
                    break;
                case 3:
                    [weakSelf.invteDict setObject:contet forKey:@"vehicleNumber"];
                    break;
                case 4:
                    [weakSelf.invteDict setObject:contet forKey:@"message"];
                    break;
                default:
                    break;
            }
            KLog(@"indexPath :%@",indexPath);
            KLog(@"cell :%@",cell);
            KLog(@"contet : %@",contet);
            
        };
        switch (section) {
            case 0:
                cell.content = self.visitFriendInfoModel.partyView.nickName;
                break;
            case 1:
                cell.content = self.visitFriendInfoModel.partyView.phone;
                break;
            case 2:
                cell.content = self.visitFriendInfoModel.partyView.email;
                break;
            case 3:
                break;
            default:
                break;
        }
        cell.isEdit = YES;
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==self.dataAry.count-1) {
        return K_FactorH(240);
    }
    return K_FactorH(60);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return K_FactorH(10);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

@end
